<?php

include 'xpfw.php';

class application extends xpfw {

    public function __construct() {
        $this->initCore();
        $this->initConstraints();
        $this->initApp();
    }

    private function initConstraints() {
        define('controllerPath', phpPath . 'controller/');
        define('viewPath', phpPath . 'view/');
        define('modelPath', phpPath . 'model/');
        //define('pluginPath', phpPath . 'plugin/');

        define('cssPath', '/public/css/');
        define('jsPath', '/public/js/');
        define('imgPath', '/public/img/');
    }

    private function initCore() {
        include 'request.php';
        include 'controller.php';
        include 'database.php';
        include 'user.php';
    }

    private function loadClasses() {
        $this->loadFiles(modelPath);
        $this->loadFiles(controllerPath);
        $this->setUser(new user);
    }

    private function initController() {
        $request = new request;
        $className = $request->getController();
        $methodName = $request->getAction();

        if (!class_exists($className))
            $this->throwError(404);

        $controller = new $className($className, $methodName);

        if (method_exists($controller, $methodName)) {
            $this->initView($controller, $methodName);
        } else {
            $this->throwError(404);
        }
    }

    public function initView($controller, $methodName) {
        try {
            $response = $controller->$methodName();
            if ($response)
                foreach ($response as $i => $v)
                    ${$i} = $v;

            $view = $controller->getViewPath();
            $user = $this->getUser();
            require viewPath . 'layout.php';
        } catch (Exception $e) {
            $this->log('Error [' . $e->getMessage() . ']', 500);
        }
    }

    private function initApp() {
        session_start();
        $this->loadClasses();
        $this->initController();
    }

}

$app = new application;
?>
